class Tools {
    /**
     * rc-form 表单验证异常对象 降纬
     */
    static flatError = (err) => {
      const hasError = {};
      Object
        .keys(err)
        .forEach((k) => {
          hasError[k] = err[k].errors[0].message;
        });
      return hasError;
    }

    /**
     * @desc 字符串加*
     * @param str 加*字符串
     * @param frontLen 字符串前面保留位
     * @param endLen 字符串后面保留位
     * @param starLen 加*长度 默认 去掉首尾保留字符串长度
     */
    static plusStar = (str, frontLen, endLen, starLen) => {
      let len = str.length - frontLen - endLen;
      if (starLen) {
        len = starLen;
      }
      let xing = '';
      for (let i = 0; i < len; i += 1) {
        xing += '*';
      }
      return str.substring(0, frontLen) + xing + str.substring(str.length - endLen);
    }

    /**
     * @desc 保留有效数字位数
     * @param {*} num
     * @param {*} isRound 是否四舍五入
     * @param {*} decimalPlaces 指数位
     */
    static fixNum(num, isRound = false, decimalPlaces = 2) {
      const nfloat = /^(-(([0-9]+\.[0-9]*[1-9][0-9*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/;
      const pfloat = /^\d+(\.\d+)?$/;
      if (nfloat.test(num) || pfloat.test(num)) {
        if (isRound) {
          return Number(num).toFixed(decimalPlaces);
        }
        const numerator = 10 ** decimalPlaces; // 分母
        const denominator = Math.floor(num * numerator); // 分子
        return (denominator / numerator).toFixed(decimalPlaces);
      }
      return NaN;
    }

    /**
     * 格式化数字
     * @param  {String} num 金额
     * @param  {String} thousands 千分位符号
     */
    static formatNum(num, thousands = ',') {
      if (typeof num === 'number') {
        return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, thousands);
      }
      return num.replace(/\B(?=(\d{3})+(?!\d))/g, thousands);
    }

    /**
     * 对象键值对转换成字符串
     * @param {Object} obj 带转换字符串
     * @param {String} joinstr 连接字符串
     * @param {String} sort 排序默认升序 'desc' 'asc'
     */
    static Object2Str = (obj, joinstr = '&', sort = 'asc') => {
      if (sort === 'asc') {
        return Object.keys(obj).sort().map(k => `${k}=${obj[k]}`).join(joinstr);
      }
    }

    /**
     * window判断当前电脑平台
     */
    static platform = () => {
      const userAgent = window.navigator.userAgent.toLocaleLowerCase();
      if (userAgent.includes('macintosh')) {
        return 'mac';
      }
      return 'window';
    }
}

export default Tools;
